package cn.edu.scnu.springbootcinema.controller;


import cn.edu.scnu.springbootcinema.entity.Comments;
import cn.edu.scnu.springbootcinema.entity.User;
import cn.edu.scnu.springbootcinema.service.CommentsService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.sql.Date;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/comments")
public class CommentsController {

    @Autowired
    private CommentsService commentService;

    @PostMapping
    public ResponseEntity<?> addComment(
            @RequestBody Comments comment,  // 直接使用实体接收
            BindingResult bindingResult,
            HttpSession session) {

        if (bindingResult.hasErrors()) {
            return ResponseEntity.badRequest().body(Map.of(
                    "code", 400,
                    "message", bindingResult.getFieldError().getDefaultMessage()
            ));
        }

        User currentUser = (User) session.getAttribute("user");
        if (currentUser == null) {
            return ResponseEntity.status(401).body(Map.of("code", 401, "message", "请先登录"));
        }

        // 设置服务端字段
        comment.setUserId(currentUser.getUserId());
        long currentTimeMillis = System.currentTimeMillis();
        comment.setCreatedDate(new Date(currentTimeMillis));

        commentService.addComment(comment);
        return ResponseEntity.ok(Map.of("code", 200, "message", "评论成功"));
    }

    @GetMapping
    public ResponseEntity<?> getComments(
            @RequestParam Integer movieId) {

        List<Comments> comments = commentService.getCommentsByMovieId(movieId);

        List<Map<String, Object>> commentList = comments.stream().map(c -> {
            Map<String, Object> map = new HashMap<>();
            map.put("id", c.getId());
            map.put("userId", c.getUserId());
            map.put("content", c.getContent());
            // 时间转换修正
            map.put("createdDate", c.getCreatedDate()
                    .toLocalDate()
                    .atStartOfDay(ZoneId.systemDefault())
                    .toInstant()
                    .toEpochMilli());
            return map;
        }).collect(Collectors.toList());

        return ResponseEntity.ok(Map.of("code", 200, "data", commentList));
    }
}
